#include "user_communication.h"

user_communication::user_communication(QWidget *parent) : QWidget(parent)
{
    setupUI();
    connectToServer();
}
user_communication::~user_communication()
{
    delete m_tcp;
}

void user_communication::setupUI()
{
    setWindowTitle("患者沟通专用");
    resize(640, 480);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    m_port = new QLineEdit(this);
    m_port->setText("8899");
    mainLayout->addWidget(m_port);

    m_record = new QTextEdit(this);
    m_record->setReadOnly(true);
    mainLayout->addWidget(m_record);

    m_msg = new QTextEdit(this);
    mainLayout->addWidget(m_msg);

    m_sendMsgButton = new QPushButton("发送", this);
    mainLayout->addWidget(m_sendMsgButton);

    m_statusBar = new QStatusBar(this);
    mainLayout->addWidget(m_statusBar);

    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/OIP-C (1).jpg").scaled(20, 20));
    m_statusBar->addWidget(new QLabel("连接状态:"));
    m_statusBar->addWidget(m_status);

    connect(m_sendMsgButton, &QPushButton::clicked, this, &user_communication::on_sendMsgButton_clicked);
}

void user_communication::connectToServer()
{
    m_tcp = new QTcpSocket(this);

    // 直接连接到服务器，硬编码 IP 地址
    m_tcp->connectToHost(QHostAddress("127.0.0.1"), m_port->text().toUShort());

    connect(m_tcp, &QTcpSocket::readyRead, this, [=](){
        QByteArray data = m_tcp->readAll();
        m_record->append("医生say: " + data);
    });

    connect(m_tcp, &QTcpSocket::disconnected, this, [=](){
        m_tcp->close();
        m_tcp->deleteLater();
        m_status->setPixmap(QPixmap(":/OIP-C (1).jpg").scaled(20, 20));
        m_record->append("沟通服务结束");
    });

    connect(m_tcp, &QTcpSocket::connected, this, [=](){
        m_status->setPixmap(QPixmap(":/OIP-C.jpg").scaled(20, 20));
        m_record->append("沟通服务开始");
    });
}

void user_communication::on_sendMsgButton_clicked()
{
    QString msg = m_msg->toPlainText();
    m_tcp->write(msg.toUtf8());
    m_record->append("患者say: " + msg);
}
